package com.bjx.flow.approve.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.bjx.api.system.domain.query.UserQuery;
import com.bjx.api.system.domain.vo.UserVO;
import com.bjx.api.system.service.RemoteUserService;
import com.bjx.common.core.constant.FrameConst;
import com.bjx.common.core.domain.R;
import com.bjx.common.core.exception.BJXException;
import com.bjx.flow.approve.user.ApprovalUserDispose;
import com.bjx.api.system.domain.bo.ExecuteBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @desc: 组织机构解析
 * @author: liushuai
 * @date: 2022/11/19 21:51
 */
@Service("orgDisposeHandler")
@Slf4j
public class OrgDisposeHandler extends ApprovalUserDispose {

    @Resource
    private RemoteUserService remoteUserService;

    @Override
    public void dispose(JSONObject jsonObject, List<UserVO> users) {
        JSONArray jsonArray = jsonObject.getJSONArray("org");
        if (CollectionUtil.isNotEmpty(jsonArray)) {
            List<ExecuteBO> executes = Convert.toList(ExecuteBO.class, jsonArray);
            Map<Long, List<Long>> map = new HashMap<>();
            for (ExecuteBO bo : executes) {
                Long orgId = Long.valueOf(bo.getValue());
                List<Long> list = Optional.ofNullable(map.get(orgId)).orElse(new ArrayList<>());
                if (ObjectUtil.isNotNull(bo.getPostId())) {
                    list.add(Long.valueOf(bo.getPostId()));
                }
                map.put(orgId, list);
            }
            R<List<UserVO>> r = remoteUserService.listUserVOByOrgAndPosts(UserQuery.builder()
                    .queryMap(map)
                    .build());
            if(r.getCode() == FrameConst.FAIL.intValue()){
                log.error("调用远程用户接口失败:{}",r.getMsg());
                throw new BJXException("调用远程用户接口失败");
            }
            List<UserVO> data = r.getData();
            users.addAll(data);
        }
        this.executeNext(jsonObject,users);
    }
}
